// 基础信息
import { loginByUsername } from '@/api/login'
import { queryUserLevel, queryUserTotal } from '@/api/basic'
import { getToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(), // 用户token
    userLevel: 'c', // 设计稿中有个C级 是看不到团队业绩的， 这里假设有两种用户等级 B级 和C级 ，C级无团队
    monthSale: 0, // 月销售额
    sumSale: 0, // 累计销售额
    monthIncome: 0, // 月收益
    sumIncome: 0, // 累计收益
    loading: true // 正在加载中
  },

  mutations: {
    // 设置 token
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    // 设置用户级别
    SET_USER_LEVEL: (state, level) => {
      state.userLevel = level // level 为 'b' || 'c'
    },
    // 设置用户累计销售额
    SET_SUM_SALE: (state, sum) => {
      state.sumSale = sum // 两位浮点数
    },
    // 设置用户月销售额
    SET_MONTH_SALE: (state, sum) => {
      state.monthSale = sum // 两位浮点数
    },
    // 设置用户累计收益
    SET_SUM_INCOME: (state, sum) => {
      state.sumIncome = sum // 两位浮点数
    },
    // 设置用户月收益
    SET_MONTH_INCOME: (state, sum) => {
      state.monthIncome = sum // 两位浮点数
    }
  },

  getters: {},

  actions: {
    // 用户名登录
    LoginByUsername ({commit}, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response.data
          commit('SET_TOKEN', data.token)
          setToken(response.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户级别
    QueryUserLevel ({commit, state}) {
      return new Promise((resolve, reject) => {
        queryUserLevel(state.token).then(response => {
          const data = response.data
          console.log(data)
          commit('SET_USER_LEVEL', data.level)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 查询用户总额 累计销售额 当月销售额 累计收益 当月收益
    QueryUserTotal ({commit, state}) {
      return new Promise((resolve, reject) => {
        queryUserTotal(state.token).then(response => {
          const data = response.data
          console.log(data)
          commit('SET_SUM_SALE', data.sumSale)
          commit('SET_MONTH_SALE', data.monthSale)
          commit('SET_SUM_INCOME', data.sumIncome)
          commit('SET_MONTH_INCOME', data.monthIncome)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
